﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using LitJson;


namespace eFrameWork.Customs
{
    public partial class HelpItems : System.Web.UI.Page
    {
        public string UserArea = "Application";
        public eAction Action;
        public eList elist;
        public eForm eform;
        public eUser user;
        public eModel model;
        public string AppItem = eParameters.Request("AppItem");       
        private string id = eParameters.QueryString("id");
        public string pid = eParameters.QueryString("pid");
        public string proid = eParameters.QueryString("proid");
        public string eTree = "";
        public string allids = "";
        string sql = "";
        public bool Ajax = false;      

        string outname = "";
        string tablename = "Help_Items";
        string primaryKey = "HelpItemID";
        string foreignKey = "ParentID";
        private eDataBase _database;
        private eDataBase DataBase
        {
            get
            {
                if (_database == null)
                {
                    if (model != null)
                    {
                        _database = model.DataBase;
                    }
                    else
                    {
                        _database=eBase.DataBase;
                    }
                }
                return _database;
            }
        }

        private DataTable _projects;
        private DataTable Projects
        {
            get
            {
                if (_projects == null)
                {
                    string sql = "select HelpProjectID,Name from Help_Projects where SiteID=" + user["SiteID"] + " and deltag=0 order by px,addtime";
                    _projects = eBase.DataBase.getDataTable(sql);
                }
                return _projects;
            }
        }
        public string ProjectList
        {
            get
            {
                StringBuilder sb = new StringBuilder();
                if (Projects.Rows.Count > 0)
                {
                    sb.Append("<div class=\"esearchgroup\">\r\n");
                    foreach (DataRow dr in Projects.Rows)
                    {
                        sb.Append("<a href=\"Custom.aspx?AppItem=" + AppItem + "&proid=" + dr["HelpProjectID"].ToString() + "\" onfocus=\"this.blur();\"" + (proid == dr["HelpProjectID"].ToString() ? " class=\"cur\"" : "") + ">" + dr["Name"].ToString() + "</a>");
                    }
                    sb.Append("</div>\r\n");
                }
                return sb.ToString();
            }
        }
        public string Type = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            
            //前端
            //htt ps://help.grapecity.com.cn/pages/viewpage.action?pageId=46172999
            //word帮助
            user = new eUser(eBase.getUserArea(UserArea));           
            eModelInfo customModel = new eModelInfo(user);
            model = customModel.Model;
            Action = new eAction(user);
            allids = getParentIDS(pid);
        
            if (Projects.Rows.Count == 0)
            {
                LitBody.Text = "<div style=\"margin:10px;color:#666;\">请先建立项目!</div>";
                return;
            }
            if (proid.Length == 0) proid = Projects.Rows[0]["HelpProjectID"].ToString();

          


            //eBase.Writeln(allids);
           
            Action.Actioning += new eActionHandler(Action_Actioning);
            Action.Listen();            
        }
        private void BindList()
        {
            if (Type != "2") return;
            if (pid.Length == 0) return;
            elist = new eList("Help_Items");

            elist.Fields.Add("HelpItemID,Name,AddTime,CASE WHEN Show=1 THEN 'images/sw_true.gif' ELSE 'images/sw_false.gif' END as ShowPIC,CASE WHEN Show=1 THEN '0' ELSE '1' END as ShowValue");
            elist.Where.Add("ParentID=" + pid);
            elist.Where.Add("SiteID=" + user["SiteID"]);
            elist.Where.Add("deltag=0");
         

            eDataTable.Power = model.Power;
            elist.OrderBy.Default = "addTime desc";//默认排序
            elist.Bind(eDataTable, ePageControl1);
            //eBase.Writeln("pid=" + pid);
            //eBase.Writeln("Type=" + Type);
        }
        private string getParentIDS(string ID)
        {
            if (ID.Length == 0) return "";
            string _back = "";
            string pid = DataBase.getValue("select " + foreignKey + " from " + tablename + " where " + primaryKey + "='" + ID + "'");
            if (pid.Length == 0)
            {
                _back = ID;
            }
            else
            {
                _back = getParentIDS(pid) + "," + ID;
            }
            return _back;
        }
        private string getTree(string ParentID,int level=0)
        {
            //eBase.Writeln(allids);
            StringBuilder sb = new StringBuilder();          

            sql = "select isnull(max(px),0) as maxpx,count(*) as ct from " + tablename + " where DelTag=0";
            sql += " and HelpProjectID=" + proid;
            sql += (ParentID.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + ParentID + "'");
            sql += " and " + (user["SiteID"].ToString().Length > 0 ? "(SiteID=0 or SiteID=" + user["SiteID"].ToString() + ")" : "SiteID=0");



            
            DataTable tb = DataBase.getDataTable(sql);
            if (tb.Rows.Count == 0) return "";
          

            if (Convert.ToInt32(tb.Rows[0]["ct"]) != Convert.ToInt32(tb.Rows[0]["maxpx"]))
            {
                /*
                sql = "update " + tablename + " set PX=(";
                sql += "select b.rownum from ";
                sql += "(";
                sql += "select ROW_NUMBER() over(order by px,addtime) as rownum," + primaryKey + ",addTime from " + tablename + " where delTag=0";
                sql += (ParentID.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + ParentID + "'");
                sql += " and " + (user["SiteID"].ToString().Length > 0 ? "(SiteID=0 or SiteID='" + user["SiteID"].ToString() + "')" : "SiteID=0");
                sql += " and HelpProjectID=" + proid;
                sql += ") as b where b." + primaryKey + "=" + tablename + "." + primaryKey ;
                sql += ")  where delTag=0";
                sql += " and HelpProjectID=" + proid;
                sql += (ParentID.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + ParentID + "'");
                sql += " and " + (user["SiteID"].ToString().Length > 0 ? "(SiteID=0 or SiteID='" + user["SiteID"].ToString() + "')" : "SiteID=0");
                DataBase.Execute(sql);
                */
            }

            sql = "select " + primaryKey + "," + foreignKey + ",Type,Name,PX,Show from " + tablename + " where DelTag=0";
            sql += " and HelpProjectID=" + proid + " and Type>0 and Type<3";
            sql += (ParentID.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + ParentID + "'");
            sql += " and " + (user["SiteID"].ToString().Length > 0 ? "(SiteID=0 or SiteID=" + user["SiteID"].ToString() + ")" : "SiteID=0");

            sql += " Order by PX,addTime";
            tb = DataBase.getDataTable(sql);


            if (pid.Length == 0 && ParentID.Length == 0 && tb.Rows.Count > 0)
            {
                pid = tb.Rows[0]["HelpItemID"].ToString();
                Type = tb.Rows[0]["Type"].ToString();
            }
            
           
            //eBase.Writeln(sql);
            //eBase.PrintDataTable(tb);
           
            if (ParentID.Length == 0)
            {
                sb.Append("<ul id=\"etree\" class=\"etree\" PID=\"NULL\">\r\n");
            }
            else
            {
                sb.Append("<ul PID=\"" + ParentID + "\"" + (("," + allids + ",").ToLower().IndexOf("," + ParentID + ",") == -1 ? " style=\"display:none;\"" : "") + ">\r\n");
            }
            foreach (DataRow dr in tb.Rows)
            {
                if (Type.Length == 0 && dr["HelpItemID"].ToString() == pid) Type = dr["Type"].ToString();
                sql = "select count(*) from  " + tablename + " where DelTag=0 and " + foreignKey + "='" + dr[primaryKey].ToString() + "'";
                sql += " and " + (user["SiteID"].ToString().Length > 0 ? "(SiteID=0 or SiteID=" + user["SiteID"].ToString() + ")" : "SiteID=0");
            
                string ct = DataBase.getValue(sql);
                sb.Append("<li oncontextmenu=\"return false;\" dataid=\"" + dr[primaryKey].ToString() + "\"");
                if (dr["Type"].ToString() == "1" && (("," + allids + ",").ToLower().IndexOf("," + dr[primaryKey].ToString().ToLower() + ",") == -1 || ct == "0"))
                {

                    sb.Append(" dataurl=\"" + (ct == "0" ? "" : "Custom.aspx?AppItem=" + AppItem + "&proid=" + proid + "&act=gethtml&pid=" + dr[primaryKey].ToString()) + "\"");
                    sb.Append(" class=\"" + (ct == "0" ? "" : "close") + "\">");
                    sb.Append("<div oncontextmenu=\"return false;\" style=\"-webkit-touch-callout:none; \" onmousedown2=\"div_contextmenu(event,this);\">");
                    sb.Append("<span title=\"显示\" class=\"show" + (dr["Show"].ToString() == "True" ? " play" : " pause") + "\" onmousedown=\"setShow(this,'" + dr[primaryKey].ToString() + "');\"></span>");
                    sb.Append("<a itemtype=\"" + dr["type"].ToString() + "\" style=\"max-width:" + (300-(level*20)-65) + "px;" + (pid == dr[primaryKey].ToString() ? "font-weight:bold;" : "") + "\" dataid=\"" + dr[primaryKey].ToString() + "\" href=\"" +  "Custom.aspx?AppItem=" + AppItem + "&proid=" + proid + "&pid=" + dr[primaryKey].ToString() + "\" ");
                    sb.Append("oncontextmenu=\"return false;\" onmousedown=\"contextmenu(event,this);\" title=\"" + dr["Name"].ToString() + "\">" + dr["Name"].ToString() + " (" + ct + ")</a>");
                    //sb.Append("<span title=\"绑定项\" class=\"binditem" + (dr["BindItem"].ToString() == "True" ? " true" : " false") + "\" onmousedown=\"setBindItem(this,'" + dr[primaryKey].ToString() + "');\"></span>");

                    sb.Append("</div>");
                }
                else
                {
                    sb.Append(" dataurl=\"\"");
                    sb.Append(" class=\"\">");
                    sb.Append("<div oncontextmenu=\"return false;\" style=\"-webkit-touch-callout:none; \" onmousedown2=\"div_contextmenu(event,this);\">");
                    sb.Append("<span title=\"显示\" class=\"show" + (dr["Show"].ToString() == "True" ? " play" : " pause") + "\" onmousedown=\"setShow(this,'" + dr[primaryKey].ToString() + "');\"></span>");
                    sb.Append("<a itemtype=\"" + dr["type"].ToString() + "\" style=\"max-width:" + (300 - (level * 20) - 65) + "px;" + (pid == dr[primaryKey].ToString() ? "font-weight:bold;" : "") + "\" dataid=\"" + dr[primaryKey].ToString() + "\" href=\"" + "Custom.aspx?AppItem=" + AppItem + "&proid=" + proid + "&pid=" + dr[primaryKey].ToString() + "\" ");
                    sb.Append("oncontextmenu=\"return false;\" onmousedown=\"contextmenu(event,this);\" title=\"" + dr["Name"].ToString() + "\">" + dr["Name"].ToString() + " (" + ct + ")</a>");
                    //sb.Append("<span title=\"绑定项\" class=\"binditem" + (dr["BindItem"].ToString() == "True" ? " true" : " false") + "\" onmousedown=\"setBindItem(this,'" + dr[primaryKey].ToString() + "');\"></span>");

                    sb.Append("</div>");
                    if (dr["Type"].ToString() == "1") sb.Append(getTree(dr[primaryKey].ToString(),level+1));
                }

                sb.Append("</li>\r\n");
            }
            sb.Append("</ul>\r\n");
            return sb.ToString();
        }
        protected void Action_Actioning(string Actioning)
        {

            eform = new eForm(tablename , user);
            eform.DataBase = DataBase;
            eform.ModelID = "1";
            if (Actioning.ToLower() == "show")
            {
                if (Request.UrlReferrer != null)
                {
                    sql = "update Help_Items set show=" + eParameters.QueryString("value") + " where HelpItemID=" + id;
                    DataBase.Execute(sql);
                    //eBase.clearDataCache("Help_Items");
                    Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                }
            }

            if (Actioning.ToLower() == "gethtml")
            {
                //Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
                Response.Write(getTree(eParameters.QueryString("pid")));
                Response.End();
                //HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            #region 是否显示
            if (Actioning.ToLower() == "setshow")
            {
                sql = "update " + tablename + " set Show='" + eParameters.QueryString("value") + "' where " + primaryKey + "='" + id + "'";
                DataBase.Execute(sql);
                Response.End();
            }
            #endregion
            if (Actioning.ToLower() == "setsort")
            {
                #region 位置
                string ParentID = eParameters.QueryString("pid").Replace("NULL", "");
                int index=Convert.ToInt32( eParameters.QueryString("index"));
                DataRow dr = DataBase.getDataTable("SELECT * FROM " + tablename + " where " + primaryKey + "='" + id + "'").Select()[0];
                string oldpid = dr[ foreignKey ].ToString();
                int oldindex = Convert.ToInt32(dr["px"]);


                if (ParentID == oldpid)//父级不变
                {
                    if (oldindex < index) //小变大
                    {
                        sql = "update " + tablename + " set PX=PX-1 where delTag=0 " + (ParentID.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + ParentID + "'") + " and PX>" + oldindex.ToString() + " and PX<=" + index.ToString();
                        sql += " and HelpProjectID=" + proid;
                        DataBase.Execute(sql);
                    }
                    else //大变小
                    {
                        sql = "update " + tablename + " set PX=PX+1 where delTag=0 " + (ParentID.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + ParentID + "'") + " and PX>=" + index.ToString() + " and PX<" + oldindex.ToString();
                        sql += " and HelpProjectID=" + proid;
                        DataBase.Execute(sql);
                    }
                    sql = "update " + tablename + " set PX='" + index.ToString() + "' where " + primaryKey + "='" + id + "'";
                    DataBase.Execute(sql);
                }
                else
                {
                    sql = "update " + tablename + " set PX=PX-1 where delTag=0 " + (oldpid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + oldpid + "'") + " and PX>" + oldindex.ToString();
                    sql += " and HelpProjectID=" + proid; 
                    DataBase.Execute(sql);

                    sql = "update " + tablename + " set PX=PX+1 where delTag=0 " + (ParentID.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + ParentID + "'") + " and PX>=" + index.ToString();
                    sql += " and HelpProjectID=" + proid; 
                    DataBase.Execute(sql);

                    sql = "update " + tablename + " set PX='" + index.ToString() + "'," + foreignKey + "=" + (ParentID.Length == 0 ? "NULL" : "'" + ParentID + "'") + " where " + primaryKey + "='" + id + "'";
                    sql += " and HelpProjectID=" + proid; 
                    DataBase.Execute(sql);



                }
                eBase.End();
                //HttpContext.Current.ApplicationInstance.CompleteRequest();
                #endregion
            }

            eTree = getTree("");
          
            if (Actioning.Length > 0)
            {
                eform.onChange += new eFormTableEventHandler(eform_onChange);
                eform.AddControl(eFormControlGroup);
                if (Actioning == "add" && eParameters.QueryString("pid").Length > 0) M1_F3.Value = eParameters.QueryString("pid");
                //if (Actioning == "edit") eform.fi
                if (Actioning == "add" && eParameters.QueryString("pid").Length == 0) Type = "";
                eform.Handle();
                if (Actioning == "edit")
                {
                    Type = DataBase.getValue("Select Type from Help_Items where HelpItemID=" + id);
                }
            }
            else
            {
                if (Request.QueryString["ajax"] != null)
                {
                    Response.Clear();
                    JsonData json = new JsonData();
                    //json.Add("body", eBase.encode(eTree));
                    json["body"] = eTree;
                    Response.Write(json.ToJson());
                    Response.End();
                    //HttpContext.Current.ApplicationInstance.CompleteRequest();
                }

                eform.AddControl(eFormControlGroup);
                if(Type=="1") eform.LoadAction("view", pid);              
            }
            BindList();
        }
        private void eform_onChange(object sender, eFormTableEventArgs e)
        {
            
            DataRow dr;
            string pid = "";
            string oldpid = "";
            int oldindex = 0;
            string maxpx = "";

            switch (e.eventType)
            {
                case eFormTableEventType.Inserting:
                    #region 添加
                    //if (user["SiteID"].ToString().Length > 0) eform.Fields.Add("SiteID", user["SiteID"].ToString());     
                    eform.Fields.Add("HelpProjectID", proid);
                    if (eParameters.Form("M1_F2").Length==0) eform.Fields.Add("Type", 0);
                    string px = eform.Fields["px"].ToString();
                        pid = eform.Fields[foreignKey].ToString();
                        maxpx = DataBase.getValue("select isnull(max(px),0) from " + tablename + " where HelpProjectID=" + proid + " and delTag=0 " + (pid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + pid + "'"));
                        maxpx=(Convert.ToInt32(maxpx)+1).ToString();
                        if (px == "" || px == "0" || px == "999999" || Convert.ToInt32(px) > Convert.ToInt32(maxpx))
                        {
                            eform.Fields["px"] = maxpx;
                        }
                        else
                        {
                            sql = "update " + tablename + " set PX=PX+1 where HelpProjectID=" + proid + " and delTag=0 " + (pid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + pid + "'") + " and PX>=" + px;
                            DataBase.Execute(sql);
                        }
                    #endregion
                        //eBase.End();
                    break;
                case eFormTableEventType.Updating:
                    if (eform.Fields.ContainsKey("Type"))
                    {
                        if (eform.Fields["Type"].ToString().Length == 0) eform.Fields["Type"] = 0;
                    }
                    //if(Type=="2") eform.Fields.Add("Type", 0);

                    break;
                    #region 修改
                   
                    dr = DataBase.getDataTable("SELECT * FROM " + tablename + " where " + primaryKey + "='" + e.ID + "'").Select()[0];
                    pid = eform.Fields[foreignKey].ToString();
                    oldpid = dr[foreignKey ].ToString();
                    oldindex = Convert.ToInt32(dr["px"]);
                    int index = Convert.ToInt32(eform.Fields["px"]);
                    if (pid == oldpid)//父级不变
                    {
                        if (oldindex < index) //小变大
                        {
                            sql = "update " + tablename + " set PX=PX-1 where delTag=0 " + (pid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + pid + "'") + " and PX>" + oldindex.ToString() + " and PX<=" + index.ToString();
                            DataBase.Execute(sql);
                        }
                        else //大变小
                        {
                            sql = "update " + tablename + " set PX=PX+1 where delTag=0 " + (pid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + pid + "'") + " and PX>=" + index.ToString() + " and PX<" + oldindex.ToString();
                            DataBase.Execute(sql);
                        }
                        maxpx = DataBase.getValue("select isnull(max(px),0) + 1 from " + tablename + " where delTag=0 " + (pid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + pid + "'"));
                        if (index > Convert.ToInt32(maxpx))
                        {
                            eform.Fields["px"] = maxpx;
                        }

                    }
                    else
                    {
                        sql = "update " + tablename + " set PX=PX-1 where delTag=0 " + (oldpid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + oldpid + "'") + " and PX>" + oldindex.ToString();
                        DataBase.Execute(sql);

                        sql = "update " + tablename + " set PX=PX+1 where delTag=0 " + (pid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + pid + "'") + " and PX>=" + index.ToString();
                        DataBase.Execute(sql);

                        maxpx = DataBase.getValue("select isnull(max(px),0) from " + tablename + " where delTag=0 " + (pid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + pid + "'"));
                        maxpx = (Convert.ToInt32(maxpx) + 1).ToString();
                        if (index > Convert.ToInt32(maxpx))
                        {
                            eform.Fields["px"] = maxpx;
                        }
                    }
                    #endregion
                    break;
                case eFormTableEventType.Deleting:
                    #region 删除
                    dr = DataBase.getDataTable("SELECT * FROM " + tablename + " where " + primaryKey + "='" + e.ID + "'").Select()[0];
                    oldpid = dr[ foreignKey ].ToString();
                    oldindex = Convert.ToInt32(dr["px"]);

                    sql = "update " + tablename + " set PX=PX-1 where delTag=0 " + (oldpid.Length == 0 ? " and " + foreignKey + " IS NULL" : " and " + foreignKey + "='" + oldpid + "'") + " and PX>" + oldindex.ToString();
                    DataBase.Execute(sql);

                    sql = "update " + tablename + " set PX='0' where " + primaryKey + "='" + e.ID + "'";
                    DataBase.Execute(sql);

                  
                    #endregion
                    break;
                case eFormTableEventType.Deleted:
                    oldpid = DataBase.getValue("SELECT " + foreignKey + " FROM " + tablename + " where " + primaryKey + "='" + e.ID + "'");

                    if (Request.QueryString["ajax"] != null)
                    {
                        eResult.Success("删除成功!");
                        //eJson json = new eJson();
                        //json.Add("success", "1");
                        //json.Add("message", "删除成功!");
                        //Response.Clear();
                        //Response.Write(json.ToString());
                        //Response.End();
                        //HttpContext.Current.ApplicationInstance.CompleteRequest();
                    }
                    else
                    {
                        string url = Request.UrlReferrer == null ? "" : Request.UrlReferrer.PathAndQuery;
                        if (Type == "1" || url.Length == 0)
                        {
                            url = "Custom.aspx?AppItem=" + AppItem;
                            //if (oldpid.Length > 0) url += "&act=view&id=" + oldpid;
                            url += "&proid=" + proid;
                            string[] arr = allids.Split(",".ToCharArray());
                            if (arr.Length > 1) url += "&pid=" + arr[arr.Length - 2];
                        }
                        Response.Redirect(url, true);
                    }
                    break;
            }
        }
        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (Request.QueryString["ajax"] != null) Ajax = Convert.ToBoolean(Request.QueryString["ajax"]);
        }
    }
}